package com.yanqu.road.server.manger.activity.bulletscreen;

import com.alibaba.fastjson.JSONArray;
import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.activity.bulletscreen.ActivityBarrageMessage;
import com.yanqu.road.entity.enums.eActivityType;
import com.yanqu.road.pb.activity.BulletScreenProto;
import com.yanqu.road.server.TempMgr;
import com.yanqu.road.server.gameplayer.module.bulletscreen.ActivityBulletScreen;
import com.yanqu.road.server.manger.activity.ActivityMgr;
import com.yanqu.road.server.manger.player.UserMgr;
import com.yanqu.road.server.manger.player.GamePlayerMgr;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.utils.YanQuMessageUtils;
import com.yanqu.road.server.protocol.CrossProtocol;
import com.yanqu.road.utils.date.DateHelper;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class ActivityBulletScreenMgr extends TempMgr {

    static Map<Integer, ActivityBulletScreen> bulletScreenMap = new ConcurrentHashMap<>();

    static Map<Integer, ActivityInfo> activityInfoMap = new ConcurrentHashMap<>();  //跨服弹幕活动

    @Override
    public boolean reloadConfig() throws Exception {
        return true;
    }

    @Override
    public boolean reloadData() throws Exception {
        return true;
    }

    @Override
    public boolean init() throws Exception {
        return reload();
    }

    @Override
    public boolean stop() {
        return false;
    }


    @Override
    public boolean save() {
        /** 消息不入库
        for (Map.Entry<Integer, ActivityBulletScreen> bulletScreenEntry : bulletScreenMap.entrySet()) {
            ActivityBulletScreen bulletScreen = bulletScreenEntry.getValue();
            List<ActivityBarrageMessage> list = bulletScreen.getMessageList();
            for (ActivityBarrageMessage msg : list) {
                if (msg.isInsertOption()) {
                    BulletScreenBusiness.addActivityBarrageMessage(msg);
                }
            }
        }*/
        return true;
    }

    /**
     * 初始或者加载弹幕数据
     * @param inShowTimeActivityInfo
     */
    public static void initOrReloadMsgData(ActivityInfo inShowTimeActivityInfo) {
        if (inShowTimeActivityInfo ==null || !ActivityMgr.activityInShowTime(inShowTimeActivityInfo)) {
            return;
        }
        if(isCrossActivity(inShowTimeActivityInfo)) {
            //跨服弹幕
            BulletScreenProto.CrossActivityInitOrReloadMsg.Builder reqMsg = BulletScreenProto.CrossActivityInitOrReloadMsg.newBuilder();
            reqMsg.setActivityId(inShowTimeActivityInfo.getActivityId());
            GamePlayerMgr.sendPacket(0, YanQuMessageUtils.buildMessage(CrossProtocol.C_CROSS_ACTIVITY_INIT_BULLET_SCREEN, reqMsg));
        }else {
            ActivityInfo activityInfo = null;
            ActivityBulletScreen activityBulletScreen = bulletScreenMap.get(inShowTimeActivityInfo.getActivityId());
            if (activityBulletScreen != null) {
                activityInfo = activityBulletScreen.getActivityInfo();
            }
            if (activityInfo == null) {
                activityBulletScreen = new ActivityBulletScreen(inShowTimeActivityInfo);
                activityBulletScreen.init();
                bulletScreenMap.put(inShowTimeActivityInfo.getActivityId(), activityBulletScreen);
            }
        }
    }


    /**
     * 弹幕
     * @param activityId
     * @param content
     * @param userId
     * @return
     */
    public static ActivityBarrageMessage addBarrageMessage(int activityId, String content, long userId) {
        ActivityBulletScreen bulletScreen = bulletScreenMap.get(activityId);
        if(bulletScreen != null){
           return bulletScreen.addBarrageMessage(content, userId);
        }
        return null;
    }

    /**
     * 添加待推送玩家
     * @param activityId
     * @param userId
     */
    public static void addMsgListener(int activityId, long userId) {
        ActivityBulletScreen bulletScreen = bulletScreenMap.get(activityId);
        if(bulletScreen != null){
            bulletScreen.addMsgListener(userId);
        }
    }

    /**
     * 获取弹幕
     * @param activityId
     * @return
     */
    public static List<ActivityBarrageMessage> getMessageList(int activityId) {
        ActivityBulletScreen bulletScreen = bulletScreenMap.get(activityId);
        if(bulletScreen != null){
            return bulletScreen.getMessageList();
        }
        return new ArrayList<>();
    }

    /**
     * 清理过期数据
     */
    public static void removeOutTimeMsg() {
        //移除过期活动的数据
        long nowTime = DateHelper.getCurrentSecond();
        for (Map.Entry<Integer, ActivityBulletScreen> bulletScreenEntry : bulletScreenMap.entrySet()) {
            ActivityBulletScreen bulletScreen = bulletScreenEntry.getValue();
            bulletScreen.removeOutTimeMsg();
            if(nowTime > bulletScreen.getActivityInfo().getEndShowTime()){
                bulletScreenMap.remove(bulletScreen.getActivityInfo().getActivityId());
            }
        }
    }

    /**
     * 同步弹幕给客户端
     */
    public static void syncBarrageMessageToClient(){
        for (Map.Entry<Integer, ActivityBulletScreen> bulletScreenEntry : bulletScreenMap.entrySet()) {
            ActivityBulletScreen bulletScreen = bulletScreenEntry.getValue();
            bulletScreen.syncBarrageMessageToClient();
        }
    }

    //======================================================

    /**
     * 是否跨服活动(跨服弹幕)
     */
    public static boolean isCrossActivity(ActivityInfo activityInfo){
        boolean isCross = false;
        if(activityInfo.getType() == eActivityType.WishPoolActivity.getValue()){
            isCross = activityInfo.getServerIdList().size() > 1;
        }
        if(activityInfo.getType() == eActivityType.SpringDinner.getValue()){
            isCross = activityInfo.getServerIdList().size() > 1;
        }
        if(activityInfo.getType() == eActivityType.FireWork2023.getValue()){
            isCross = activityInfo.getServerIdList().size() > 1;
        }
        if(isCross){
            if(!activityInfoMap.containsKey(activityInfo.getActivityId())){
                activityInfoMap.put(activityInfo.getActivityId(), activityInfo);
            }
        }
        return isCross;
    }

    /**
     * 是否跨服活动(跨服弹幕)
     */
    public static boolean isCrossActivity(int activityId){
        return activityInfoMap.containsKey(activityId);
    }

    public static BulletScreenProto.ActivityBarrageMessageTemp.Builder parseBarrageMessageBuilder(ActivityBarrageMessage msg, String content, int activityId) {
        BulletScreenProto.ActivityBarrageMessageTemp.Builder temp = BulletScreenProto.ActivityBarrageMessageTemp.newBuilder();
        temp.setActivityId(activityId);
        temp.setContent(content);
        temp.setContentId(msg.getContentId());
        temp.setPostTime(msg.getPostTime());
        temp.setUserId(msg.getUserId());
        return temp;
    }

    public static BulletScreenProto.BulletScreenContentListRespMsg.Builder getMsgListBuilder(List<ActivityBarrageMessage> syncList) {
        BulletScreenProto.BulletScreenContentListRespMsg.Builder respMsg = BulletScreenProto.BulletScreenContentListRespMsg.newBuilder();
        respMsg.setRet(0);
        for(ActivityBarrageMessage msg : syncList){
            BulletScreenProto.ActivityBarrageMessageTemp.Builder temp = ActivityBulletScreenMgr.parseBarrageMessageBuilder(msg, msg.getContent(), msg.getActivityId());
            temp.setNickName(UserMgr.getNickName(msg.getUserId()));
            respMsg.addMsg(temp);
        }
        return respMsg;
    }

    /**
    * 描述：变更玩家弹幕
    * 作者：zrq
    * 时间：2022/8/5
    * 参数：
    活动编号，玩家编号，变更内容
    * 返回值：
    **/
    public static int changePlayerBulletScreen(int activityId, long userId, String content, long contentId) {
        ActivityBulletScreen bulletScreen = bulletScreenMap.get(activityId);
        if (null == bulletScreen) {
            return GameErrorCode.E_ACTIVITY_NO_FOUND;
        }
        return bulletScreen.changePlayerMsg(userId, content, contentId);
    }

    public static JSONArray queryPlayerBulletScreen(int activityId, long userId) {
        ActivityBulletScreen bulletScreen = bulletScreenMap.get(activityId);
        if (null == bulletScreen) {
            return new JSONArray();
        }
        return bulletScreen.queryPlayerMsg(userId);
    }
}
